package com.antaohua.framework.web.filter;

import java.io.IOException;
import java.util.UUID;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.MDC;
import org.springframework.web.filter.OncePerRequestFilter;

public class LoggerMDCFilter extends OncePerRequestFilter implements Filter {
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
    try
    {
//      MDC.put("loginUserId", "demo-loginUsername");


      MDC.put("req.requestURI", StringUtils.defaultString(request.getRequestURI()));
      MDC.put("req.queryString", StringUtils.defaultString(request.getQueryString()));
      MDC.put("req.requestURIWithQueryString", request.getRequestURI() + (request.getQueryString() == null ? "" : new StringBuilder("?").append(request.getQueryString()).toString()));
      MDC.put("req.remoteAddr", StringUtils.defaultString(request.getRemoteAddr()));

      MDC.put("req.id", StringUtils.remove(UUID.randomUUID().toString(), "-"));
      chain.doFilter(request, response);
    } finally {
      clearMDC();
    }
  }

  private void clearMDC()
  {
    if (MDC.getContext() != null)
      MDC.getContext().clear();
  }
}